package zwp.exercise.service.exercisedemo.chapterFour;

import java.util.Scanner;

/**
 * @Author zwp14
 * @create 2025/11/11 22:46
 * @description 斐波纳契数列
 */
public class FibonacciSequenceExerciseDemo {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您要查找的斐波那契数列的位数：");
        int inNum = scanner.nextInt();

        // 递归实现
//        long endNum = fibonacciMethodFirst(inNum);
        // for循环实现
        long endNum = fibonacciMethodTwo(inNum);
        // 还有两种方法，第一种是在for循环的基础上加上map进行缓存，第二种是通过矩阵实现


        System.out.println("第" + inNum + "位数的值为：" + endNum);
        scanner.close();
    }

    private static long fibonacciMethodTwo(int inNum) {
        int a = 0;
        int b = 1;
        int c;
        if (inNum == 0){
            return 0;
        } else if (inNum == 1) {
            return 1;
        }
        for (int i = 2; i <= inNum; i++) {
            c = a + b;
            a = b;
            b = c;
        }
        return b;
    }

    private static long fibonacciMethodFirst(int inNum) {
        if (inNum == 0){
            return 0;
        } else if (inNum == 1) {
            return 1;
        }
        return fibonacciMethodFirst(inNum -1) + fibonacciMethodFirst(inNum - 2);
    }
}
